<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import request from '@/utils/request'
import { ElMessage, ElDatePicker } from 'element-plus'

const route = useRoute()
const router = useRouter()
const doctor = ref(null)
const loading = ref(false)
const selectedDate = ref('')
const availableTimes = ref([])
const selectedTime = ref('')
const patientName = ref('')
const patientPhone = ref('')
const symptoms = ref('')

// 获取医生信息
async function fetchDoctorInfo() {
  loading.value = true
  try {
    const { data } = await request.get(`/api/doctors/${route.params.doctorId}`)
    if (data && data.code === 0) {
      doctor.value = data.data
    }
  } catch (error) {
    console.error('获取医生信息失败:', error)
    ElMessage.error('获取医生信息失败')
  } finally {
    loading.value = false
  }
}

// 获取可预约时间
async function fetchAvailableTimes() {
  if (!selectedDate.value) return
  
  try {
    const { data } = await request.get(`/api/doctors/${route.params.doctorId}/times`)
    
    if (data && data.code === 0) {
      // 处理时间数据结构
      const times = data.data.available_times || []
      const selectedDateTimes = times.find(t => t.date === selectedDate.value)
      
      if (selectedDateTimes) {
        const allTimes = []
        // 添加上午时间
        if (selectedDateTimes.morning) {
          selectedDateTimes.morning.forEach(slot => {
            if (slot.available) {
              allTimes.push(slot.time)
            }
          })
        }
        // 添加下午时间
        if (selectedDateTimes.afternoon) {
          selectedDateTimes.afternoon.forEach(slot => {
            if (slot.available) {
              allTimes.push(slot.time)
            }
          })
        }
        availableTimes.value = allTimes
      } else {
        availableTimes.value = []
      }
    }
  } catch (error) {
    console.error('获取可预约时间失败:', error)
    ElMessage.error('获取可预约时间失败')
  }
}

// 提交预约
async function submitAppointment() {
  if (!selectedDate.value || !selectedTime.value || !patientName.value || !patientPhone.value) {
    ElMessage.warning('请填写完整预约信息')
    return
  }
  
  try {
    const { data } = await request.post('/api/appointments/', {
      doctor_id: route.params.doctorId,
      date: selectedDate.value,
      time: selectedTime.value,
      appointment_date: selectedDate.value,
      appointment_time: selectedTime.value,
      appointment_type: 'consultation',

      patient_name: patientName.value,

      symptoms: symptoms.value,
      patient_phone: patientPhone.value
    })
    
    if (data && data.code === 0) {
      ElMessage.success('预约成功！正在跳转到我的预约...')

      // 延迟跳转，让用户看到成功消息
      setTimeout(() => {
        router.push('/my-appointments')
      }, 1500)
    } else {
      ElMessage.error(data.msg || '预约失败')
      ElMessage.success('预约成功！')
      // 可以跳转到预约记录页面
    }
  } catch (error) {
    console.error('预约失败:', error)
    ElMessage.error('预约失败')
    if (error.response?.status === 401) {
      ElMessage.error('请先登录后再预约')
      router.push('/login')
    } else {
      ElMessage.error(error.response?.data?.msg || '预约失败')
    }
  }
}

// 初始化获取医生信息
onMounted(() => {
  fetchDoctorInfo()
})
</script>

<template>
  <div class="doctor-appointment-page" v-loading="loading">
    <div v-if="doctor" class="doctor-info">
      <h2>{{ doctor.name }} - {{ doctor.title }}</h2>
      <p>{{ doctor.department }} {{ doctor.hospital }}</p>
      <p>{{ doctor.specialty }}</p>
      <p>{{ doctor.description }}</p>
    </div>
    
    <div class="appointment-form">
      <h3>预约信息</h3>
      
      <div class="form-item">
        <label>选择日期</label>
        <el-date-picker 
          v-model="selectedDate" 
          type="date" 
          value-format="YYYY-MM-DD"
          placeholder="选择预约日期"
          @change="fetchAvailableTimes"
          :disabled-date="(date) => date < new Date()"
        />
      </div>
      
      <div class="form-item" v-if="selectedDate && availableTimes.length > 0">
        <label>选择时间</label>
        <div class="time-slots">
          <div 
            v-for="time in availableTimes" 
            :key="time"
            class="time-slot"
            :class="{ 'selected': selectedTime === time }"
            @click="selectedTime = time"
          >
            {{ time }}
          </div>
        </div>
      </div>
      
      <div class="form-item">
        <label>患者姓名</label>
        <el-input v-model="patientName" placeholder="请输入患者姓名" />
      </div>
      
      <div class="form-item">
        <label>患者电话</label>
        <el-input v-model="patientPhone" placeholder="请输入患者电话" />
      </div>
      
      <div class="form-item">
        <label>症状描述</label>
        <el-input 
          v-model="symptoms" 
          type="textarea" 
          :rows="3" 
          placeholder="请描述您的症状"
        />
      </div>
      <div class="submit-section">
        <div class="appointment-tip">
          💡 预约成功后将自动跳转到"我的预约"页面，您可以在那里查看和管理所有预约记录
        </div>
        <el-button
          type="primary"
          size="large"
          @click="submitAppointment"
          :disabled="!selectedDate || !selectedTime || !patientName || !patientPhone"
        >
          提交预约
        </el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.doctor-appointment-page {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.doctor-info {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.doctor-info h2 {
  margin: 0 0 10px 0;
}

.doctor-info p {
  margin: 5px 0;
  color: #606266;
}

.appointment-form {
  margin-top: 30px;
}

.form-item {
  margin-bottom: 20px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
}

.time-slots {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.time-slot {
  padding: 8px 15px;
  background: #f5f7fa;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.time-slot:hover {
  background: #e1e5eb;
}

.time-slot.selected {
  background: #409eff;
  color: white;
}

.submit-section {
  margin-top: 30px;
  text-align: center;
}

.appointment-tip {
  background: #f0f9ff;
  border: 1px solid #b3e5fc;
  border-radius: 4px;
  padding: 12px;
  margin-bottom: 15px;
  color: #1976d2;
  font-size: 14px;
  line-height: 1.4;
}
</style>